package com.top10.controller;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sun.org.apache.regexp.internal.RE;
import com.top10.bean.JwtUtil;
import com.top10.bean.PageBean;
import com.top10.bean.ResponseBean;
import com.top10.common.Const;
import com.top10.entity.Goods;
import com.top10.entity.GoodsDetailed;
import com.top10.entity.UserCart;
import com.top10.service.IGoodsDetailedService;
import com.top10.service.IGoodsService;
import com.top10.service.IUserCartService;
import com.top10.utils.RandomUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.Errors;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 购物车Controller
 *
 * @author ellen
 * @version 1.0
 * @date 2018/10/8
 */
@RestController
@RequestMapping("/manager/cart")
public class CartController {

    @Autowired
    IUserCartService userCartService;
    @Autowired
    IGoodsService goodsService;
    @Autowired
    private IGoodsDetailedService iGoodsDetailedService;

    /**
     * 添加购物车
     *
     * @param userCart
     * @return
     */
    @RequestMapping("/addCart")
    public ResponseBean addCart(@Valid UserCart userCart, Errors errors, HttpServletRequest request) {
        String userUuid = JwtUtil.getUuidByToken(request); //获取用户的uuid
        if (errors.hasErrors()) {
            return ResponseBean.createError(errors.getFieldError().getDefaultMessage());
        }

        Goods goods = goodsService.selectOne(new EntityWrapper<Goods>().eq("uuid", userCart.getGoodsUuid()));
        if (goods == null) {
            return ResponseBean.createError("找不到该商品");
        }


        GoodsDetailed stock=iGoodsDetailedService.selectOne(new EntityWrapper<GoodsDetailed>().eq("isdeleted",Const.IsNotDelete)
                .eq("goods_uuid",userCart.getGoodsUuid()));
        if(stock==null){
            return ResponseBean.createSuccess("库存中不存在"+goods.getName()+"该商品");
        }
        if(stock.getStock()==0 || stock.getStock()<userCart.getQuantity()){
            return ResponseBean.createSuccess(goods.getName()+"库存没有这么多件商品");
        }

        String[] line = userCart.getSkukey().split(",");
        List<UserCart> originUserCart = userCartService.selectList(new EntityWrapper<UserCart>()
                .eq("user_uuid", userUuid)
                .eq("goods_uuid", userCart.getGoodsUuid())
                .eq("isdeleted", 0));
        int d=0;
        if(originUserCart.size()!=0){
            for(int i=0;i<=originUserCart.size()-1;i++){
                int c = -1;
                for (int j = 0; j <= line.length - 1; j++) {
                    if (originUserCart.get(i).getSkukey().contains(line[j])) {
                        c++;
                        if (c == line.length - 1) {
                            Integer num = originUserCart.get(i).getQuantity();
                            num += userCart.getQuantity();
                            originUserCart.get(i).setQuantity(num);
                            originUserCart.get(i).setUpdatetime(new Date());
                            userCartService.updateById(originUserCart.get(i));
                            d++;
                        }
                    }
                }
            }
        }



        Boolean rest = false;
          if(d==0){
              userCart.setUuid(RandomUtils.makeUUID());
              userCart.setUserUuid(userUuid);
              userCart.setIsdeleted(false);
              userCart.setCreatetime(new Date());
              userCart.setCreator(userUuid);
             rest= userCartService.insert(userCart);
          }
        if(rest || d!=0){
            return ResponseBean.createSuccess().addData("userCart",userCart);
        }else{
              return ResponseBean.createError("加入购物车失败");
        }
    }







    /**
     * 购物车列表
     *
     * @return
     */
    @RequestMapping("/cartList")
    public ResponseBean cartList(HttpServletRequest request, PageBean pageBean) {
        List shopList1=new ArrayList();

       String userUuid = JwtUtil.getUuidByToken(request);
      // String userUuid="95153988018047CFA4D466F799FA9C4E";
        Page page = PageHelper.startPage(pageBean.getPageNum(), pageBean.getPageSize());
        List shopList = userCartService.cartList(userUuid);
        for(int i=shopList.size()-1;i>=0;i--){
            shopList1.add(shopList.get(i));
        }
        pageBean = new PageBean(page.getPageNum(), page.getPageSize(), (int) page.getTotal());

        return ResponseBean.createSuccess().addData("shopList", shopList1).addData("pageBean", pageBean);
    }

    /**
     * 购物车删除商品
     *
     * @param goodsUuids
     * @return
     */
    @RequestMapping("/delete")
    public ResponseBean delete(String goodsUuids, String skukeys, HttpServletRequest request) {
        if (goodsUuids == null || goodsUuids.trim().equals("")) {
            return ResponseBean.createError("至少选择一个商品");
        }
        if (skukeys == null) {
            return ResponseBean.createError("skukeys值不能为空");
        }

        String[] goodsUuidsArr = goodsUuids.split(",");
        String[] skukeysArr = skukeys.split(";");

        if(goodsUuidsArr.length != skukeysArr.length){
            return ResponseBean.createError("goodsUuids和skukeys的长度不匹配");
        }

        int i=0;
        for (String goodsUuid : goodsUuidsArr) {
            Goods goods = goodsService.selectOne(new EntityWrapper<Goods>().eq("uuid", goodsUuid));
            if (goods == null) {
                return ResponseBean.createError("找不到该商品");
            }

            String userUuid = JwtUtil.getUuidByToken(request);
            List<UserCart> userCarts = userCartService.selectList(new EntityWrapper<UserCart>()
                    .eq("user_uuid", userUuid)
                    .eq("goods_uuid", goodsUuid)
                    .eq("skukey", skukeysArr[i])
                    .eq("isdeleted", 0));
            if (userCarts == null) {
                return ResponseBean.createError("找不到该记录");
            }
            for(UserCart userCart : userCarts){
                userCart.setIsdeleted(true);
                userCart.setUpdatetime(new Date());
                userCartService.updateById(userCart);
            }
            i++;
        }

        return ResponseBean.createSuccess().setMessage("删除成功");
    }




    /**
     * 修改商品数量
     *
     * @param request
     * @param goodsUuids
     * @param quantities
     * @return
     */
    @RequestMapping("/updateQuantity")
    public ResponseBean updateQuantity(HttpServletRequest request, String goodsUuids, String quantities,String cuuid) {
        if (goodsUuids == null || goodsUuids.trim().equals("")) {
            return ResponseBean.createError("至少选择一个商品");
        }

        if (quantities == null || quantities.trim().equals("")) {
            return ResponseBean.createError("数量quantities");
        }

        String[] goodsUuidsArr = goodsUuids.split(",");
        String[] quantitiesArr = quantities.split(",");
        String[] cuuidArr = cuuid.split(",");
        if (goodsUuidsArr.length != quantitiesArr.length) {
            return ResponseBean.createError("goodsUuids数量和quantities数量不匹配");
        }
        if (goodsUuidsArr.length != cuuidArr.length) {
            return ResponseBean.createError("goodsUuids数量和cuuid数量不匹配");
        }
        for (int i = 0; i < goodsUuidsArr.length; i++) {
            Goods goods = goodsService.selectOne(new EntityWrapper<Goods>().eq("uuid", goodsUuidsArr[i]));
            if (goods == null) {
                return ResponseBean.createError("找不到该商品");
            }

            String userUuid = JwtUtil.getUuidByToken(request);
            UserCart userCart = userCartService.selectOne(new EntityWrapper<UserCart>()
                    .eq("user_uuid", userUuid)
                    .eq("uuid", cuuidArr[i])
                    .eq("isdeleted", 0));
            if (userCart == null) {
                return ResponseBean.createError("找不到该记录");
            }
            GoodsDetailed stock=iGoodsDetailedService.selectOne(new EntityWrapper<GoodsDetailed>().eq("isdeleted",Const.IsNotDelete)
                    .eq("goods_uuid",goodsUuidsArr[i]));
            if(stock==null){
                return ResponseBean.createSuccess("库存中不存在"+goods.getName()+"该商品");
            }
            if(stock.getStock()==0 || stock.getStock()<Integer.parseInt(quantitiesArr[i])){
                return ResponseBean.createSuccess(goods.getName()+"库存没有这么多件商品");
            }
            userCart.setQuantity(Integer.parseInt(quantitiesArr[i]));
            userCart.setUpdatetime(new Date());
            userCartService.updateById(userCart);
        }


        return ResponseBean.createSuccess().setMessage("修改成功");
    }

    /**
     * 修改商品规格
     *
     * @param request
     * @param goodsUuid
     * @param skukey
     * @param attribute
     * @return
     */
    @RequestMapping("/updateAttribute")
    public ResponseBean updateAttribute(HttpServletRequest request, String goodsUuid, String skukey, String attribute,String cuuid,Integer quantity) {
        String userUuid = JwtUtil.getUuidByToken(request);
        if (goodsUuid == null || goodsUuid.trim().equals("")) {
            return ResponseBean.createError("至少选择一个商品");
        }
        if (skukey == null || skukey.trim().equals("")) {
            return ResponseBean.createError("skukey不能为空");
        }
        if (attribute == null || attribute.trim().equals("")) {
            return ResponseBean.createError("attribute不能为空");
        }
        if (cuuid == null || cuuid.trim().equals("")) {
            return ResponseBean.createError("cuuid不能为空");
        }

       /* Goods goods = goodsService.selectOne(new EntityWrapper<Goods>().eq("uuid", goodsUuid));
        if (goods == null) {
            return ResponseBean.createError("找不到该商品");
        }*/

        UserCart userCart = userCartService.selectOne(new EntityWrapper<UserCart>()
                .eq("user_uuid", userUuid)
                .eq("uuid", cuuid)
                .eq("isdeleted", 0));
        String[] line = skukey.split(",");
        List<UserCart> userCartList = userCartService.selectList(new EntityWrapper<UserCart>().eq("user_uuid", userUuid).eq("isdeleted", 0));
        int d = 0;
        if(userCartList.size()!=0){
            for (int i = 0; i <= userCartList.size() - 1; i++) {
                int c = -1;
                for (int j = 0; j <= line.length - 1; j++) {
                    if (userCartList.get(i).getSkukey().contains(line[j])) {
                        c++;
                        if (c == line.length - 1) {
                            if(!userCart.getUuid().equals(userCartList.get(i).getUuid())){
                                userCartList.get(i).setQuantity(userCartList.get(i).getQuantity() + quantity);
                                userCartService.updateById(userCartList.get(i));
                                userCart.setIsdeleted(true);
                                userCartService.updateById(userCart);
                                d++;
                            }

                        }
                    }
                }
            }
        }

        Boolean rest = false;
        if (d == 0) {
            userCart.setSkukey(skukey);
            userCart.setAttribute(attribute);
            userCart.setUpdatetime(new Date());
            rest = userCartService.updateById(userCart);
        }
           if(rest || d!=0){
            return ResponseBean.createSuccess("修改成功").addData("userCart",userCart);
           }else{
            return ResponseBean.createError("修改失败");
           }
    }

}